package com.ruoyi.jihuo.handler;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collections;
import java.util.List;

@MappedTypes(List.class)
@MappedJdbcTypes(JdbcType.VARCHAR) // MySQL JSON 类型实际存储为 VARCHAR
public class JsonListTypeHandler extends BaseTypeHandler<List<String>> {
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i,
                                    List<String> parameter, JdbcType jdbcType) throws SQLException {
        try {
            // 将 List 序列化为 JSON 字符串（空列表转为 "[]"）
            String json = parameter.isEmpty() ? "[]" : JSON.toJSONString(parameter);
            ps.setString(i, json);
        } catch (Exception e) {
            throw new SQLException("Failed to convert List to JSON", e);
        }
    }

    @Override
    public List<String> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String json = rs.getString(columnName);
        return parseJson(json);
    }

    @Override
    public List<String> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String json = rs.getString(columnIndex);
        return parseJson(json);
    }

    @Override
    public List<String> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String json = cs.getString(columnIndex);
        return parseJson(json);
    }

    private List<String> parseJson(String json) throws SQLException {
        if (json == null || json.isEmpty() || json.equals("null")) {
            return Collections.emptyList(); // 返回空列表而不是 null
        }
        try {
            // 反序列化 JSON 字符串为 List
            return JSON.parseObject(json, new TypeReference<List<String>>() {});
        } catch (Exception e) {
            throw new SQLException("Failed to parse JSON to List", e);
        }
    }
}